import React, { useCallback } from 'react';
import { 
  Space, 
  Select, 
  Button, 
  Tooltip, 
  Switch, 
  Dropdown,
  Badge,
  message
} from 'antd';
import {
  ArrowRightOutlined,
  SettingOutlined,
  BookOutlined,
  FormatPainterOutlined,
  ClearOutlined
} from '@ant-design/icons';
import { useAnalysisContext, useAnalysisActions } from '../../context/AnalysisContext';
import { getSqlExamples, formatSql } from '../../services/api';

const { Option } = Select;

const AnalysisConfigSection: React.FC = () => {
  const { state } = useAnalysisContext();
  const actions = useAnalysisActions();

  const {
    sourceDbType,
    targetDbType,
    sqlContent,
    analysisConfig
  } = state;

  // 支持的数据库类型
  const supportedDatabases = [
    { value: 'ORACLE', label: 'Oracle', icon: '🔶' },
    { value: 'MYSQL', label: 'MySQL', icon: '🐬' },
    { value: 'POSTGRESQL', label: 'PostgreSQL', icon: '🐘' },
    { value: 'SQLSERVER', label: 'SQL Server', icon: '🏢' },
    { value: 'GOLDENDB', label: 'GoldenDB', icon: '🟨' },
  ];

  // SQL示例数据
  const sqlExamples = [
    {
      id: 'oracle-basic',
      name: 'Oracle基础查询',
      description: '包含Oracle特有函数的基础查询',
      expectedIssues: 3,
      content: `-- Oracle示例SQL
SELECT
    u.user_id,
    u.username,
    NVL2(u.email, u.email, 'N/A') as email_display,
    ROWNUM as row_num
FROM users u
WHERE ROWNUM <= 10
ORDER BY u.created_date NULLS LAST;`
    },
    {
      id: 'oracle-complex',
      name: 'Oracle复杂查询',
      description: 'DECODE、CONNECT BY等复杂语法',
      expectedIssues: 5,
      content: `-- Oracle复杂查询示例
SELECT 
    employee_id,
    employee_name,
    DECODE(status, 1, 'Active', 2, 'Inactive', 'Unknown') as status_desc,
    LEVEL as hierarchy_level
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
ORDER BY LEVEL, employee_name;`
    }
  ];

  // 处理数据库类型变更
  const handleSourceDbChange = useCallback((value: string) => {
    actions.setSourceDbType(value);
    actions.clearAnalysisResult();
  }, [actions]);

  const handleTargetDbChange = useCallback((value: string) => {
    actions.setTargetDbType(value);
    actions.clearAnalysisResult();
  }, [actions]);


  // 加载SQL示例
  const handleLoadExample = useCallback((example: any) => {
    actions.setSqlContent(example.content);
    actions.clearAnalysisResult();
    message.success(`已加载示例：${example.name}`);
  }, [actions]);

  // 格式化SQL
  const handleFormatSql = useCallback(async () => {
    if (!sqlContent.trim()) {
      message.warning('请先输入SQL语句');
      return;
    }

    try {
      const response = await formatSql(sqlContent, sourceDbType);

      if (response.data.success) {
        actions.setSqlContent(response.data.formattedSql);
        message.success('SQL格式化完成');
      } else {
        message.error(response.data.errorMessage || '格式化失败');
      }
    } catch (error) {
      console.error('格式化SQL失败:', error);
      message.error('格式化失败，请检查SQL语法');
    }
  }, [sqlContent, sourceDbType, actions]);

  // 清空SQL
  const handleClearSql = useCallback(() => {
    actions.setSqlContent('');
    actions.clearAnalysisResult();
    message.success('已清空SQL内容');
  }, [actions]);

  // 获取数据库选项
  const getDatabaseOptions = (excludeType?: string) => {
    return supportedDatabases
      .filter(db => db.value !== excludeType)
      .map(db => (
        <Option key={db.value} value={db.value}>
          <Space>
            <span>{db.icon}</span>
            <span>{db.label}</span>
          </Space>
        </Option>
      ));
  };

  return (
    <div className="analysis-config">
      {/* 左侧：数据库选择 */}
      <div className="config-left">
        {/* 数据库选择器 */}
        <div className="database-selector">
          <Select
            value={sourceDbType}
            onChange={handleSourceDbChange}
            style={{ width: 140 }}
            size="small"
          >
            {getDatabaseOptions(targetDbType)}
          </Select>
          
          <ArrowRightOutlined className="database-arrow" />
          
          <Select
            value={targetDbType}
            onChange={handleTargetDbChange}
            style={{ width: 140 }}
            size="small"
          >
            {getDatabaseOptions(sourceDbType)}
          </Select>
        </div>
      </div>

      {/* 右侧：工具按钮 */}
      <div className="config-right">
        <Space size="small">
          {/* SQL示例下拉菜单 */}
          <Dropdown
            menu={{
              items: sqlExamples.map(example => ({
                key: example.id,
                label: (
                  <Space>
                    <Badge 
                      count={example.expectedIssues || 0} 
                      size="small" 
                      color={example.expectedIssues > 5 ? 'red' : example.expectedIssues > 2 ? 'orange' : 'green'}
                    />
                    <div>
                      <div style={{ fontWeight: 500 }}>{example.name}</div>
                      <div style={{ fontSize: 12, color: '#666' }}>{example.description}</div>
                    </div>
                  </Space>
                ),
                onClick: () => handleLoadExample(example)
              }))
            }}
            placement="bottomRight"
          >
            <Button 
              icon={<BookOutlined />} 
              size="small"
              className="toolbar-btn"
            >
              示例SQL
            </Button>
          </Dropdown>

          {/* 格式化按钮 */}
          <Tooltip title="格式化SQL (Ctrl+F)">
            <Button
              icon={<FormatPainterOutlined />}
              onClick={handleFormatSql}
              size="small"
              className="toolbar-btn"
              disabled={!sqlContent.trim()}
            >
              格式化
            </Button>
          </Tooltip>

          {/* 清空按钮 */}
          <Tooltip title="清空SQL内容">
            <Button
              icon={<ClearOutlined />}
              onClick={handleClearSql}
              size="small"
              className="toolbar-btn"
              disabled={!sqlContent.trim()}
            >
              清空
            </Button>
          </Tooltip>

          {/* 实时分析开关 */}
          <Tooltip title={analysisConfig.enableRealTimeAnalysis ? '实时分析已开启' : '手动分析模式'}>
            <Switch
              checked={analysisConfig.enableRealTimeAnalysis}
              onChange={(checked) => actions.updateAnalysisConfig({ enableRealTimeAnalysis: checked })}
              checkedChildren="实时"
              unCheckedChildren="手动"
              size="small"
            />
          </Tooltip>

          {/* 设置按钮 */}
          <Tooltip title="分析设置">
            <Button
              icon={<SettingOutlined />}
              size="small"
              className="toolbar-btn"
              onClick={() => {
                // TODO: 打开设置弹窗
                message.info('设置功能开发中');
              }}
            >
              设置
            </Button>
          </Tooltip>
        </Space>
      </div>
    </div>
  );
};

export default AnalysisConfigSection;